package aiprogrammingassistant;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.texteditor.ITextEditor;
import org.osgi.framework.BundleContext;

import com.example.aiprogrammingassistant.views.AIToolView;

public class Activator extends AbstractUIPlugin {
    private ISelectionListener selectionListener;

    @Override
    public void start(BundleContext context) throws Exception {
        super.start(context);
        
        // 注册选择监听器
        selectionListener = new ISelectionListener() {
            @Override
            public void selectionChanged(IWorkbenchPart part, ISelection selection) {
                if (part instanceof ITextEditor && selection instanceof ITextSelection) {
                    ITextSelection textSelection = (ITextSelection) selection;
                    String code = textSelection.getText();
                    
                    // 更新所有打开的AI视图
                    PlatformUI.getWorkbench().getDisplay().asyncExec(() -> {
                        IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
                        for (IWorkbenchWindow window : windows) {
                            IWorkbenchPage page = window.getActivePage();
                            if (page != null) {
                                AIToolView view = (AIToolView) page.findView(AIToolView.ID);
                                if (view != null) {
                                    view.updateContent(code);
                                }
                            }
                        }
                    });
                }
            }
        };
        
        // 绑定到全局选择服务
        getWorkbench().getActiveWorkbenchWindow().getSelectionService()
            .addPostSelectionListener(selectionListener);
    }

    @Override
    public void stop(BundleContext context) throws Exception {
        // 移除监听器
        getWorkbench().getActiveWorkbenchWindow().getSelectionService()
            .removePostSelectionListener(selectionListener);
        super.stop(context);
    }
}